package fr.curriculumvitae.anthony.stephan.activities;

import fr.curriculumvitae.anthony.stephan.R;
import fr.curriculumvitae.anthony.stephan.pinnedsections.PinnedSectionListView;
import fr.curriculumvitae.anthony.stephan.pinnedsections.PinnedSectionListView.PinnedSectionListAdapter;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class DetailsActivity extends ListActivity {

	private static Activity context;

	private static int sectionID = -1;
	private static boolean needResult = false;
	
	private static int labelsArrayID = -1;
	private static int[] itemsArraysID = null;
	private static int colorID = -1;
	private static int activityNameID = -1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// dismiss action bar
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		
        // set content view
		setContentView(R.layout.pinned_head_list);
		context = this;
		
        // get extras
		Bundle extras = getIntent().getExtras();
		if(extras != null) {
			sectionID = extras.getInt("sectionID");
			needResult = extras.getBoolean("needResult");
			labelsArrayID = extras.getInt("labelsArrayID");
			itemsArraysID = extras.getIntArray("itemsArraysID");
			colorID = extras.getInt("colorID");
			activityNameID = extras.getInt("activityNameID");
		}

		// initialize listview
		initializeListView();
		initializeAdapter();
		
		// adapt width & height (with max limits if needed)
        final ListView listView = (ListView) findViewById(android.R.id.list);
        ViewTreeObserver vto = listView.getViewTreeObserver(); 
        vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() { 
            @SuppressWarnings("deprecation")
			@Override 
            public void onGlobalLayout() { 
            	listView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                int layoutHeight = listView.getMeasuredHeight(); 
                
                DisplayMetrics metrics = getResources().getDisplayMetrics();
                int activityFinalWidth = (int) (metrics.widthPixels * 0.90);
                int activityFinalHeight = (int) (metrics.heightPixels * 0.75);
                if(layoutHeight<=activityFinalHeight) {
                	activityFinalHeight = layoutHeight;
                }
                getWindow().setLayout(activityFinalWidth, activityFinalHeight);
            } 
        });
        
	}

	private void initializeListView() {
		getListView().setPadding(0, 0, 0, 0);
		((PinnedSectionListView)getListView()).setShadowVisible(false);
	}

	private void initializeAdapter() {
		setListAdapter(new SimpleAdapter(this, android.R.layout.simple_list_item_1, android.R.id.text1));
	}
	
	
	/////////////
	// ADAPTER //
	/////////////

	private static class SimpleAdapter extends ArrayAdapter<Training> implements PinnedSectionListAdapter {

		public SimpleAdapter(Context context, int resource, int textViewResourceId) {
			super(context, resource, textViewResourceId);

			String[] sectionLabels;
			int sectionsNumber;
			if(labelsArrayID != -1) {
				sectionLabels = context.getResources().getStringArray(labelsArrayID);
				sectionsNumber = sectionLabels.length;
			} else {
				sectionLabels = new String[]{context.getResources().getString(activityNameID)};
				sectionsNumber = sectionLabels.length;
			}
			prepareSections(sectionsNumber);

			int sectionPosition = 0, listPosition = 0;

			for(char i=0; i<sectionsNumber; i++) {
				Training section = new Training(Training.SECTION, sectionLabels[i]);
				section.sectionNumber = i;
				section.sectionPosition = sectionPosition;
				section.listPosition = listPosition++;
				onSectionAdded(section, sectionPosition);
				add(section);

				String[] items = context.getResources().getStringArray(itemsArraysID[i]);
				for(int j=0; j<items.length; j++) {
					Training item = new Training(Training.ITEM, items[j]);
					item.sectionNumber = i;
					item.sectionPosition = sectionPosition;
					item.listPosition = listPosition++;
					add(item);
				}
				sectionPosition++;
			}
		}

		protected void prepareSections(int sectionsNumber) {
			/* nothing to do */
		}

		protected void onSectionAdded(Training section, int sectionPosition) { 
			/* nothing to do */
		}

		@Override 
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			View view = null;
			Training item = getItem(position);

			if(item.type == Training.SECTION) {
				view = inflater.inflate(R.layout.layout_header, null);
				TextView tvSkillLavel = (TextView) view.findViewById(R.id.textView_skill_header_label);
				tvSkillLavel.setText(item.label);
				view.setBackgroundColor(parent.getResources().getColor(colorID));
				view.setTag(null);

			} else if(item.type == Training.ITEM) {
				view = inflater.inflate(R.layout.layout_row_training_detail, null);
				if(needResult && sectionID != -1) {
					view.setTag(position);
					view.setOnClickListener(onViewClickListener);
				}
				((TextView) view).setText(item.label);
			}

			return view;
		}

		@Override 
		public int getViewTypeCount() {
			return 2;
		}

		@Override 
		public int getItemViewType(int position) {
			return getItem(position).type;
		}

		@Override
		public boolean isItemViewTypePinned(int viewType) {
			return viewType == Training.SECTION;
		}
	}


	@SuppressWarnings("unused")
	private static class Training {
		public static final int ITEM = 0;
		public static final int SECTION = 1;
		public int sectionNumber;
		public int sectionPosition;
		public int listPosition;

		public final int type;
		public final String label;

		public Training(int type, String label) {
			this.type = type;
			this.label = label;
		}
		@Override 
		public String toString() {
			return label;
		}
	}
	
	
	  ///////////////
	 // LISTENERS //
	///////////////
	
	private static OnClickListener onViewClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			Intent result = new Intent();
			result.putExtra("sectionID", sectionID);
			result.putExtra("position", (Integer) v.getTag());
			context.setResult(RESULT_OK, result);
			context.finish();
		}
	};

}
